package com.dq.service;

import com.dq.cache.constant.CacheConstant;
import com.dq.cache.MyRedisComponent;
import com.dq.context.Constant;

import com.dq.domain.sys.section.SysSection;
import com.dq.domain.sys.user.user.base.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @创建人 gewenzhen
 * @创建时间 2019/9/9
 * @描述
 */
@Service
public class ShiroService {
    @Autowired
    MyRedisComponent myRedisComponent;

    public Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public String getToken() {
        return SecurityUtils.getSubject().getPrincipal() + "";
    }

    public SysUser getUser() {
        String token = getToken();
        SysUser sysUser = (SysUser) myRedisComponent.get(CacheConstant.USER_TOKEN_CACHE_PREFIX + token);
        return sysUser;
    }

    public boolean isSuperAdmin() {
        return getUser().getUsername().equals(Constant.ADMIN_CODE);
    }

    public Long getUserId() {
        return getUser().getId();
    }

    public SysSection getDept() {
        return getUser().getSection();
    }

    public Long getDeptId() {
        return getDept().getId();
    }

    public void setCaptchaCache(String captcha) {
        myRedisComponent.set(CacheConstant.CAPTCHA_CACHE_PREFIX + captcha, captcha, CacheConstant.CAPTCHA_CACHE_EXPIRE);
    }
    public String getCaptchaCache(String key) {
        return myRedisComponent.get(CacheConstant.CAPTCHA_CACHE_PREFIX + key) + "";
    }

    public void setSmsCaptchaCache(String smsCode, String phone) {
        myRedisComponent.set(CacheConstant.SMS_CAPTCHA_CACHE_PREFIX + phone, smsCode, CacheConstant.SMS_CAPTCHA_CACHE_EXPIRE);
    }
    public String getSmsCaptchaCache(String key) {
        return myRedisComponent.get(CacheConstant.SMS_CAPTCHA_CACHE_PREFIX + key) + "";
    }

    public boolean isLogin() {
        return getUser() != null;
    }
    public void logout() {
        SecurityUtils.getSubject().logout();
    }
}
